package com.javabi.boardgame.game.chess;

import java.util.Arrays;
import java.util.List;

import com.javabi.boardgame.game.chess.piece.ChessPiece;
import com.javabi.boardgame.game.chess.piece.PieceType;
import com.javabi.boardgame.model.IBoardGame;
import com.javabi.boardgame.model.IPlayer;
import com.javabi.boardgame.model.board.IBoard;
import com.javabi.boardgame.model.board.grid.GridLocation;
import com.javabi.boardgame.model.status.IStatus;
import com.javabi.boardgame.model.status.StatusMap;

public class ChessGame implements IBoardGame {

	private final ChessBoard board = new ChessBoard();
	private final StatusMap<ChessStatus> statusMap = new StatusMap<ChessStatus>();

	public ChessGame() {

		// Setup players
		setupPlayer(ChessPlayer.WHITE);
		setupPlayer(ChessPlayer.BLACK);
	}

	private void setupPlayer(ChessPlayer player) {
		ChessStatus status = new ChessStatus(player);
		newPieces(player.getColor(), status);
		statusMap.put(player, status);
	}

	private void setupBlackPlayer() {
		ChessPlayer player = ChessPlayer.BLACK;
		ChessStatus status = new ChessStatus(player);
		newPieces(player.getColor(), status);
		statusMap.put(player, status);
	}

	private void newPieces(ChessColor color, ChessStatus status) {

		// Back row
		int y = (color == ChessColor.WHITE) ? 1 : 8;
		newPiece(new ChessPiece(color, PieceType.ROOK), status, 'A', y);
		newPiece(new ChessPiece(color, PieceType.KNIGHT), status, 'B', y);
		newPiece(new ChessPiece(color, PieceType.BISHOP), status, 'C', y);
		newPiece(new ChessPiece(color, PieceType.QUEEN), status, 'D', y);
		newPiece(new ChessPiece(color, PieceType.KING), status, 'E', y);
		newPiece(new ChessPiece(color, PieceType.BISHOP), status, 'F', y);
		newPiece(new ChessPiece(color, PieceType.KNIGHT), status, 'G', y);
		newPiece(new ChessPiece(color, PieceType.ROOK), status, 'H', y);

		// Pawns
		y = (color == ChessColor.WHITE) ? 2 : 7;
		for (int x = 1; x <= 8; x++) {
			newPiece(new ChessPiece(color, PieceType.PAWN), status, x, y);
		}
	}

	private void newPiece(ChessPiece piece, ChessStatus status, char xChar, int y) {
		int x = GridLocation.convert(xChar, 8);
		newPiece(piece, status, x, y);
	}

	private void newPiece(ChessPiece piece, ChessStatus status, int x, int y) {
		GridLocation location = new GridLocation(x, y);
		board.setPiece(location, piece);
		status.addPiece(piece);
	}

	@Override
	public String getName() {
		throw new UnsupportedOperationException();
	}

	@Override
	public List<? extends IPlayer> getPlayerList() {
		return Arrays.asList(ChessPlayer.WHITE, ChessPlayer.BLACK);
	}

	@Override
	public IBoard<?, ?> getBoard() {
		return board;
	}

	@Override
	public IStatus getStatus(IPlayer player) {
		return statusMap.get(player);
	}

}
